package com.itheima.blog.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.api.client.AdminClient;
import com.itheima.api.client.dto.CategoryDto;
import com.itheima.api.client.dto.TagDto;
import com.itheima.blog.util.UserThreadLocalUtils;
import com.itheima.blog.web.domain.po.TAlbum;
import com.itheima.blog.web.domain.po.TBlog;
import com.itheima.blog.web.domain.query.BlogPageQuery;
import com.itheima.blog.web.dao.TBlogMapper;
import com.itheima.blog.web.service.ITAlbumService;
import com.itheima.blog.web.service.ITBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.domain.PageResDto;
import com.itheima.common.domain.R;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import com.itheima.common.domain.TCategory;
import com.itheima.common.domain.TTag;
import com.itheima.common.domain.dto.BlogPageDto;
import com.itheima.common.domain.po.ResBlog;
import com.itheima.common.domain.vo.BlogVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.itheima.api.client.vo.BlogContributionVO;
import com.itheima.api.client.vo.ProvinceBLogNum;
import com.itheima.api.client.vo.TBlogByCategoryID;
import com.itheima.api.client.vo.TBlogByTagID;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

/**
 * <p>
 * 博客文章表 服务实现类
 * </p>
 *
 * @author hyf
 * @since 2023-07-12
 */
@Service
public class TBlogServiceImpl extends ServiceImpl<TBlogMapper, TBlog> implements ITBlogService {
@Autowired
private AdminClient adminClient;
@Autowired
private ITAlbumService albumService;
    @Autowired
    private TBlogMapper tBlogMapper;
    @Override
    public R getBlogDetail(Long blogId) {
        TBlog blog = this.getById(blogId);
        if (blog!=null){
            BlogVo blogVo = new BlogVo();
            BeanUtils.copyProperties(blog,blogVo);
            String categoryId = blog.getCategoryId();
            String tagId = blog.getTagId();
            TCategory category = adminClient.getCategoryById(Long.valueOf(categoryId));
            TTag tag = adminClient.getTagById(Long.valueOf(tagId));
            blogVo.setTag(tag.getContent());
            blogVo.setCategory(category.getName());
            return R.ok(blogVo);

        }else {
            return R.error("查询不到该博客");
        }

    }

    @Override
    public List<String> getBlogNameList(Long categoryId) {
        List<TBlog> list = lambdaQuery().eq(TBlog::getCategoryId, categoryId).orderByDesc(TBlog::getClickCount).list();
        List<String> titleList = list.stream().map(TBlog::getTitle).limit(10).collect(Collectors.toList());
        return titleList;
    }

    @Override
    public R getBlogList(BlogPageDto pageReqDto) {
        Integer sortBy = pageReqDto.getSortBy();
        if (sortBy==1){
            //热度
            IPage<TBlog> tBlogIPage = lambdaQuery().orderByDesc(TBlog::getClickCount).page(new Page<>()).setPages(pageReqDto.getPage()).setSize(pageReqDto.getSize());
            PageResDto pageResDto = new PageResDto<>();
            long total = tBlogIPage.getTotal();
            long current = tBlogIPage.getCurrent();
            List<TBlog> records = tBlogIPage.getRecords();
            List<ResBlog> list = new ArrayList<>();
            for (TBlog record : records) {
                ResBlog resBlog = new ResBlog();
                BeanUtils.copyProperties(record,resBlog);
                String categoryName = adminClient.getCategoryById(Long.valueOf(record.getCategoryId())).getName();
                String imageUrl = albumService.getImageUrl(Long.valueOf(record.getFileId()));
                resBlog.setCategory(categoryName);
                resBlog.setImageUrl(imageUrl);
                list.add(resBlog);
            }
            pageResDto.setData(list);
            pageResDto.setTotal((int) total);
            pageResDto.setSize((int) tBlogIPage.getSize());
            pageResDto.setCurrentPage((int) current);
            return R.ok(pageResDto);
        }else{
            //默认
            IPage<TBlog> tBlogIPage = lambdaQuery().orderByDesc(TBlog::getCreateTime).page(new Page<>()).setPages(pageReqDto.getPage()).setSize(pageReqDto.getSize());
            PageResDto pageResDto = new PageResDto<>();
            long total = tBlogIPage.getTotal();
            long current = tBlogIPage.getCurrent();
            List<TBlog> records = tBlogIPage.getRecords();
            List<ResBlog> list = new ArrayList<>();
            for (TBlog record : records) {
                ResBlog resBlog = new ResBlog();
                BeanUtils.copyProperties(record,resBlog);
                System.out.println(record.getCategoryId());
                String categoryName = adminClient.getCategoryById(Long.valueOf(record.getCategoryId())).getName();
                String imageUrl ="";
                if (record.getFileId()!=null){
                    imageUrl = albumService.getImageUrl(Long.valueOf(record.getFileId()));
                }
                resBlog.setCategory(categoryName);
                resBlog.setImageUrl(imageUrl);
                list.add(resBlog);
            }
            pageResDto.setData(list);
            pageResDto.setTotal((int) total);
            pageResDto.setSize((int) tBlogIPage.getSize());
            pageResDto.setCurrentPage((int) current);
            return R.ok(pageResDto);
        }
    }

    @Override
    public List queryBlogByCategoryId(List<Integer> ids) {
        List<TBlog> list = lambdaQuery().in(TBlog::getCategoryId, ids).list();
        return list;
    }

    @Override
    public Long getBlogs() {
        long count = this.count();
        return count;
    }

    @Override
    public List<TBlogByTagID> getTBlogByTagID() {

        return tBlogMapper.getTBlogByTagID();
    }

    @Override
    public List<TBlogByCategoryID> getTBlogByCategoryID() {
        return tBlogMapper.getTBlogByCategoryID();
    }

    @Override
    public List<BlogContributionVO> getBlogContributions() {
        List<BlogContributionVO> list = new ArrayList<BlogContributionVO>();
        //当前时间月份的结束时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endDateTime = now.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        //当前时间的前一年的月份的开始时间
        LocalDateTime minus = now.minus(1, ChronoUnit.YEARS);
        LocalDateTime beginDateTime = minus.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
        while(endDateTime.isAfter(beginDateTime)){
            //当前天数的开始时间
            LocalDateTime todayStart= beginDateTime.with(LocalTime.MIN);
            LocalDateTime todayEnd= beginDateTime.with(LocalTime.MAX);
            String  dateStart=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:ss:mm").format(todayStart);
            String  dateEnd=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:ss:mm").format(todayEnd);
            String  bDateTime=DateTimeFormatter.ofPattern("yyyy-MM-dd").format(beginDateTime);
            BlogContributionVO blogContributionVO = new BlogContributionVO();
            blogContributionVO.setDateTime(bDateTime);
            Long count = lambdaQuery().between(TBlog::getCreateTime, dateStart, dateEnd)
                    .count();
            blogContributionVO.setCount(count.intValue());
            list.add(blogContributionVO);
            beginDateTime = beginDateTime.plusDays(1);
        }
        return list;
    }

    @Override
    public List<ProvinceBLogNum> getProvinceBLogNum(Integer classify) {
        LocalDateTime now = LocalDateTime.now();

        LocalDateTime todayStart= now.with(LocalTime.MIN);
        LocalDateTime todayEnd= now.with(LocalTime.MAX);


        if (classify == 2) {
            todayStart = now.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
            todayEnd = now.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        } else if (classify == 3) {
            todayStart = LocalDateTime.of(LocalDate.from(LocalDateTime.now().with(TemporalAdjusters.firstDayOfYear())), LocalTime.MIN);
            todayEnd = LocalDateTime.of(LocalDate.from(LocalDateTime.now().with(TemporalAdjusters.lastDayOfYear())), LocalTime.MAX);
        }
        String  dateStart=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:ss:mm").format(todayStart);
        String  dateEnd=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:ss:mm").format(todayEnd);
        return tBlogMapper.getProvinceBLogNum(dateStart,dateEnd);
    }
    @Override
    public PageResDto<TBlog> getBlogPages(BlogPageQuery blogPageQuery) {
        //获取博客标题
        String title = blogPageQuery.getTitle();
        //获得分类名称
        String categoryName = blogPageQuery.getCategoryName();
        Integer categoryId = null;
        if (categoryName != null){
            CategoryDto categoryDto = adminClient.getCategoryByName(categoryName);
            categoryId = categoryDto.getId();
        }
        //通过feign接口查询分类
        /*CategoryDto categoryDto = adminClient.getCategoryByName(categoryName);
        categoryId = categoryDto.getId();*/
        //获取标签名称
        String tagName = blogPageQuery.getTagName();
        Integer tagId = null;
        if (tagName != null){
            TagDto tagDto = adminClient.getTagByName(tagName);
            tagId = tagDto.getId();
        }
        //通过feign接口查询标签
        /*TagDto tagDto = adminClient.getTagByName(tagName);
        Integer tagId = tagDto.getId();*/
        //根据标签名称获取标签id
        Page<TBlog> page = lambdaQuery().like(TBlog::getTitle, title)
                .eq(categoryId != null, TBlog::getCategoryId, categoryId)
                .eq(tagId != null, TBlog::getTagId, tagId)
                .page(blogPageQuery.toMpPageDefaultSortByCreateTimeDesc());
        List<TBlog> blogList = page.getRecords();
        //总数
        Integer total = (int) page.getTotal();
        //当前页
        Integer current = (int) page.getCurrent();
        //每页显示条数
        Integer pages = (int) page.getPages();
        PageResDto<TBlog> blogPageResDto = new PageResDto<TBlog>();
        blogPageResDto.setTotal(total);
        blogPageResDto.setCurrentPage(current);
        blogPageResDto.setSize(pages);
        blogPageResDto.setData(blogList);
        return blogPageResDto;
    }

    @Override
    public void add(TBlog tBlog) {
        tBlog.setCreateTime(LocalDateTime.now());
        tBlog.setUpdateTime(LocalDateTime.now());
        tBlogMapper.insert(tBlog);
    }

    @Override
    @ApiOperation("根据id修改")
    public void updateBlog(TBlog tBlog,Long blogId) {
        /*blogMapper.updateBlog(tBlog, blogId);*/
        lambdaUpdate()
                .set(TBlog::getTitle, tBlog.getTitle())
                .set(TBlog::getSummary, tBlog.getSummary())
                .set(TBlog::getContent, tBlog.getContent())
                .set(TBlog::getTagId, tBlog.getTagId())
                .set(TBlog::getClickCount, tBlog.getClickCount())
                .set(TBlog::getCollectCount, tBlog.getCollectCount())
                .set(TBlog::getFileId, tBlog.getFileId())
                .set(TBlog::getStatus, tBlog.getStatus())
                .set(TBlog::getCreateTime, tBlog.getCreateTime())
                .set(TBlog::getAdminUid, tBlog.getAdminUid())
                .set(TBlog::getIsOriginal, tBlog.getIsOriginal())
                .set(TBlog::getAuthor, tBlog.getAuthor())
                .set(TBlog::getArticlesPart, tBlog.getArticlesPart())
                .set(TBlog::getCategoryId, tBlog.getCategoryId())
                .set(TBlog::getIsPublish, tBlog.getIsPublish())
                .set(TBlog::getOpenComment, tBlog.getOpenComment())
                .set(TBlog::getType, tBlog.getType())
                .set(TBlog::getUserId, tBlog.getUserId())
                .set(TBlog::getArticleSource, tBlog.getArticleSource())
                .set(TBlog::getProvince, tBlog.getProvince())
                .eq(TBlog::getId,blogId)
                .update();
    }



    @Override
    public void deleteBlog(Long blogId) {
        //获取用户端的UserId
        Integer webUserId = UserThreadLocalUtils.getWebUserId();
        //根据ID查询信息
        TBlog tBlogs = this.getById(blogId);
        String userId = tBlogs.getUserId();
        Integer userIds = Integer.valueOf(userId);
        if (webUserId.equals(userIds) ) {
            this.removeById(tBlogs.getId());
        }

    }



    @Override
    public List<TAlbum> getImages() {
        return albumService.list(new LambdaQueryWrapper<TAlbum>().eq(TAlbum::getUserId, UserThreadLocalUtils.getWebUserId()));
    }


    @Override
    public boolean putBlog(TBlog comment) {
        return updateById(comment);
    }

    @Override
    public boolean putBlogIsPush(TBlog tBlog) {
        return updateById(tBlog);
    }

    @Override
    public boolean changeBlogComment(TBlog comment) {
        return updateById(comment);
    }

    @Override
    public boolean chengePublish(TBlog tBlog) {
        return updateById(tBlog);
    }
}
